import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { GetAllPictureService, GetFileByAttributeService } from "@/service";

interface IInitialState {
  articleImages: any[];
  shopImages: any[];
  images: any[];
  total: number;
}

export const fetchPicturesThunk = createAsyncThunk(
  "fetch/picturesThunk",
  async (_, { dispatch }) => {
    const res = await GetAllPictureService();
    dispatch(SaveImageActions(res.data.images));
    return res.data;
  }
);

export const fetchPicturesFileThunk = createAsyncThunk<any, any>(
  "fetch/picturesFileThunk",
  async (data, { dispatch }) => {
    const res: any = await GetFileByAttributeService(data);
    dispatch(SaveImgFileDataActions(res.data));
    return res.data;
  }
);

const initialState: IInitialState = {
  articleImages: [],
  shopImages: [],
  images: [],
  total: 0,
};

const fileSlice = createSlice({
  name: "file",
  initialState,
  reducers: {
    SaveImageActions(state, { payload }) {
      // console.log("payload SaveImageActions ", payload);
      // let shopArr: any[] = [];
      // let artucleArr: any[] = [];
      // for (let i = 0; i < payload.length; i++) {
      //   payload[i].active = false;
      //   if (payload[i].type === "article") {
      //     artucleArr.push(payload[i]);
      //   } else {
      //     shopArr.push(payload[i]);
      //   }
      // }
      // state.articleImages = artucleArr;
      // state.shopImages = shopArr;
      // state.images = payload;
    },
    SaveImgFileDataActions(state, { payload }) {
      console.log("first save ", payload);
      state.images = payload.list;
      state.total = payload.total;
    },
    ResetImageActions(state) {
      state.images = [];
    },
  },
});

export const { SaveImageActions, SaveImgFileDataActions, ResetImageActions } =
  fileSlice.actions;
export default fileSlice.reducer;
